/**
 * Class: LNRewriter
 *		Rewrites urls based on rules in Trewrites tables
 */

/**
 * Method: Constructor
 *		Creates a rewriter instnace for a given site
 *
 * Parameters:
 *		sql typeof LNSql - sql handle of given site
 */
function LNRewriter(sql)
{
	this.sql=sql;
	this.init();
}

/**
 * Method: init
 *		Initializes rewriter, filling-in data from database
 */
LNRewriter.prototype.init=function() {
	this.rewrites=this.sql.execute_and_fetch("rewrites/list");
	for (var i=0;i<this.rewrites.length;i++) {
		var r=this.rewrites[i];
		if (r.fields!=null) r.fields=r.fields.split(/\s*,\s*/);
		r.regexp=new RegExp(r.regexp);
	}
}

/**
 * Method: work
 *		Processes given URL
 *
 * Parameteres:
 *		rr typeof rr - An object with request-response data
 */
LNRewriter.prototype.work=function(rr) {
	if (rr.action==null) throw new Error("action==null!");
	//if (rr.site.code=="che-harcho.vcity.ru") throw new Error(rr.Dumper({action:rr.action,rewrites:this.rewrites,site:rr.site.code}));
	for (var i=0;i<this.rewrites.length;i++) {
		var r=this.rewrites[i];
		var arr;
		if (!(arr=rr.action.match(r.regexp))) continue;
		rr.std_rewrite=true;
		rr.std_rewrite_fields={};
		var k=1;
		if (r.fields!=null) {
			for (var j=0;j<r.fields.length;j++) {
				rr.fields[r.fields[j]]=decodeURIComponent(arr[k]);
				k++;
				rr.std_rewrite_fields[r.fields[j]]=1;
			}
		}
		if (r.alias) {
			rr.action=r.alias;
			if (r.controller_mode) {
				rr.fields.mode=r.controller_mode;
				rr.std_rewrite_fields.mode=1;
			}
		} else {
			rr.prerun_output=rr.C(r.controller_name,rr.fields.mode||r.controller_mode);
			rr.action=rr.rewriten_action;
		}
		return;
	}
}

exports.LNRewriter=LNRewriter;
